package com.h.blog.common.interceptor;

import com.h.blog.common.constant.Constants;
import com.h.blog.common.unit.JwtUnits;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从 Header中进行查找token令牌
        String userToken = request.getHeader(Constants.USER_TOKEN_HEADER_KEY);
        log.info("从Header中获取token: {}",userToken);
        if(userToken == null) {
            response.setStatus(401);
            return false;
        }
        Claims claims = JwtUnits.parseToken(userToken);
        if(claims == null) {
            response.setStatus(401);
            return false;
        }
        return true;
    }
}
